﻿using Newtonsoft.Json;
using System.Net.WebSockets;
using System.Text;

namespace DongFangGuoKai.WCSPlatform.WebApi.Utils.WebSocketCommon
{
    /// <summary>
    /// WebSocketHandler 类用于处理客户端发来的消息 并保持连接状态
    /// </summary>
    public class WebSocketHandler
    {
        private readonly WebSocketConnectManager connectionManager;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="connectionManager"></param>
        public WebSocketHandler(WebSocketConnectManager connectionManager)
        {
            this.connectionManager = connectionManager;
        }

        /// <summary>
        /// 处理客户端发送的消息  并保持连接不中断
        /// </summary>
        /// <param name="webSocket"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Handle(WebSocket webSocket, HttpContext context,string id)
        {
            var buffer = new byte[1024 * 4];
            // 接收客户端发送的消息
            var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            while (!result.CloseStatus.HasValue) //result.CloseStatus 是一个可空枚举类型的属性，用于表示 WebSocket 连接的关闭状态。
            {
                // 将接收到的消息原样发送回客户端
                await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

                // 继续接收下一条消息
                result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }
            // 关闭 WebSocket 连接
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
            //移除
            connectionManager.RemoveSocket(id);
        }
    }
}
